<template>
  <div class="app-container charts"  v-loading="loading">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="70px" :rules="rules">
      <el-form-item label="设备类型" prop="machineTypeId">
        <el-select v-model="queryParams.machineTypeId" placeholder="请选择制造类型" @change="machineTypeIdChange" style="width: 150px">
            <el-option
                    v-for="dict in machineTypeIdOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
            />
        </el-select>
      </el-form-item>

      <el-form-item label="主线名称" prop="mainLineName">
        <el-select v-model="queryParams.mainLineName" placeholder="请选择制造类型" clearable style="width: 150px">
            <el-option
                    v-for="dict in mainLineNameOptions"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
            />
        </el-select>
      </el-form-item>

      <el-form-item label="日期基准" prop="endTime">
        <WeekTimePicker type="date" v-model="queryParams.dataTime" style="width: 150px"/>
        <el-button style="margin-left: 10px;" type="primary" icon="Search" @click="getData">查询</el-button>
      </el-form-item>
    </el-form>
    <div id="chart_line" style="width: 100%; height: 550px;" v-show="isShow"></div>

    <t-ag-grid
      v-show="isShow"
      :style="{height: tableHeight}"
      style="margin-top: -300px;"
      :column-defs="column"
      :row-data="tableData"
      :row-buffer="20"
      align="center"
      :defaultColDef = "{
          suppressMenu:true
      }"
      header-align="center"
      @cell-clicked="onCellClicked"
      />

  </div>
</template>

<script setup name="MachineAST">
  import { listHeatMapLine } from "@/api/indexAnalyse/machineAST"
  import { getEqpTypeId } from '@/common/affect'
  import { heatMapOptions } from './heatMap'
  import { lineOptions } from './line'
  import { getTableColumns } from "./table"
  const { proxy } = getCurrentInstance()
  import moment from 'moment'
  import * as echarts from 'echarts'

  import { useRoute, useRouter } from 'vue-router'
  const route = useRoute()
  const router = useRouter()

  const queryParams = reactive({
    machineTypeId: null,
    mainLineName: null,
    dataTime: moment().subtract(1, 'days').format('YYYY-MM-DD')
  })

  const machineTypeIdOptions = ref([
    { label: 'MBB线 ', value: 'MBB线' },
    { label: '叠瓦线', value: '叠瓦线' }
    // { label: 'ACF线', value: 'ACF线' }
  ])

  const mainLineNameOptions = ref([])

  const rules = {
    machineTypeId: [
      { required: true, message: "制造类型不能为空", trigger: "change" }
    ],
    mainLineName: [
      { required: true, message: "主线名称不能为空", trigger: "change" }
    ]
  }

  const column = ref()
  const tableData = ref()
  const tableHeight = ref()

  const isShow = ref(false)
  const loading = ref(false)

  let lineChart = null
  let heatMapChart = null

  onActivated(() => {
    let state = history?.state
    if(state.machineTypeId && state.mainLineName){
      queryParams.machineTypeId = state.machineTypeId
      queryParams.mainLineName = state.mainLineName
      queryParams.dataTime = state.dataTime
      getData()
      // 获取主线名称 options
      // getEqpTypeId({
      //   machineType: queryParams.machineTypeId,
      //   isAnalysis: 'Y'
      // }).then((res) => {
      //   res.data.forEach(item => {
      //     mainLineNameOptions.value.push({
      //       label: item.machineId,
      //       value: item.machineId
      //     })
      //   })
      // })
    }
  })
  onMounted(() => {
    lineChart = echarts.getInstanceByDom(document.getElementById("chart_line"))
    const resizeObserver = new ResizeObserver((entries, b) => {
      if(lineChart){
        lineChart.resize()
      }
      if(heatMapChart){
        heatMapChart.resize()
      }
    })
    resizeObserver.observe(document.getElementById("chart_line"))
    if(!lineChart){
      lineChart = echarts.init(document.getElementById("chart_line"))
    }

  })

  const getData = () => {

    proxy.$refs.queryRef.validate(valid => { // 表单校验
      if (valid) {
        loading.value = true
        queryParams.dataTime = moment(queryParams.dataTime).format('YYYY-MM-DD')

        listHeatMapLine({
          machineId: queryParams.mainLineName, // special: machineId传主线名称
          dataTime: queryParams.dataTime
        }).then((res) => {
          loading.value = false

          if(res.rows.length){
            isShow.value = true
            const queryData = res.rows
            const { lineOption } = lineOptions(queryData, queryParams.machineTypeId, moment(queryParams.dataTime).format('MM-DD'))
            lineChart.setOption(lineOption)

            const { columns,  target } = getTableColumns(queryData)
            column.value = columns
            tableData.value = target
            tableHeight.value = `${(tableData.value.length * 32) + 41}px`

            column.value.forEach((item) => {
              item.cellStyle = cellStyle
            })
          } else {
            isShow.value = false
          }

        })

      }
    })
  }

  const cellStyle = ({ colDef, data, value }) => {
    if(colDef.headerName === '设备ID'){
      return {
        color: 'blue',
        fontWeight: 'bold',
        textDecoration: 'underline'
      }
    }

    if(colDef.headerName !== '基准值' && typeof value === 'number'){
      if(value > data.rfctenDayAst){
        if(data.rfctenDayAst * 1.05 > value && value >= data.rfctenDayAst){
          return {
            background: '#ff9999'
          }
        }
        if(data.rfctenDayAst * 1.15 > value && value >= data.rfctenDayAst * 1.05){
          return {
            background: '#ff5050'
          }
        }
        if(value >= data.rfctenDayAst * 1.15){
          return {
            background: '#cc0000'
          }
        }
      } else if(value < data.rfctenDayAst){
        if(value < data.rfctenDayAst && value >= data.rfctenDayAst * 0.95){
          return {
            background: '#66ff66'
          }
        }
        if(value < data.rfctenDayAst * 0.95 && value >= data.rfctenDayAst * 0.85){
          return {
            background: '#33cc33'
          }
        }
        if(value <= data.rfctenDayAst * 0.85){
          return {
            background: '#008000'
          }
        }
      }
    }
  }

  // data.rfctenDayAst   value

  // const cellStyle = (params) => {
  //   console.log('params', params)
  // }

  const onCellClicked = ({ colDef, value }) => {
    if(colDef.headerName === '设备ID'){
      router.push({
        path: '/indexAnalyse/astAnalysis/astTenDay',
        query: {
          machineTypeId: queryParams.machineTypeId,
          // mainLineName: `H05-${params.value}`,
          mainLineName: value
        }
      })
    }
  }

  const machineTypeIdChange = () => {
    queryParams.mainLineName = null
    mainLineNameOptions.value = []
    getEqpTypeId({
      machineType: queryParams.machineTypeId,
      isAnalysis: 'Y'
    }).then((res) => {
      res.data.forEach(item => {
        mainLineNameOptions.value.push({
          label: item.machineId,
          value: item.machineId
        })
      })
    })
  }

</script>

<style lang="less" scoped>
.charts {
  overflow-y: scroll;
}
</style>